package org.streets.eis.setting.converters;

import java.util.Locale;

import org.apache.wicket.Application;
import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.util.convert.IConverter;
import org.apache.wicket.util.convert.converters.AbstractConverter;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.string.Strings;


public class StringConverter extends AbstractConverter {
	private static final long serialVersionUID = 1L;

	public StringConverter(){
	}
	
	public String convertToObject(String value, Locale locale){
		if (Strings.isEmpty(value)){
			return null;
		}
		return value;
	}

	@Override
	public String convertToString(final Object value, Locale locale){
		if (value == null){
			return "";
		}
		if (String.class.isAssignableFrom(value.getClass())){
			return (String)value;
		}
			
		IConverter converter = Application.get().getConverterLocator().getConverter(value.getClass());
		if (converter!=null){
            return converter.convertToString(value, locale);
		}				

		try{
			return (String)Objects.convertValue(value, String.class);
		} catch (Exception e){
			throw new ConversionException("Could not convert object of type: " +
				value.getClass() + " to string. Possible its #toString() returned null. " +
				"Either install a custom converter (see IConverterLocator) or " +
				"override #toString() to return a non-null value.").setSourceValue(value)
				.setConverter(this);
		}		
	}

	@Override
	protected Class<String> getTargetType()
	{
		return String.class;
	}
	
}
